import { defineStore } from 'pinia'
import { computed } from 'vue'

export const useSSEStore = defineStore('sse', () => {
	// 存储接收到的消息
	const messages = ref([])
	// SSE 连接实例
	const eventSource = ref(null)
	// 连接状态
	const isConnected = ref(false)
	// 错误信息
	const error = ref(null)
	// 消息订阅者
	const subscribers = ref(new Map())

	// 获取最新消息
	const latestMessage = computed(() => {
		return messages.value.length > 0 ? messages.value[messages.value.length - 1] : null
	})

	// 获取特定类型的消息
	const getMessagesByType = (type) => {
		return messages.value.filter((msg) => msg.type === type)
	}

	// 获取特定类型的最新消息
	const getLatestMessageByType = (type) => {
		const filtered = messages.value.filter((msg) => msg.type === type)
		return filtered.length > 0 ? filtered[filtered.length - 1] : null
	}

	// 添加消息
	const addMessage = (message) => {
		messages.value.push(message)
		// 通知所有订阅者
		notifySubscribers(message)
	}

	// 设置连接状态
	const setConnected = (connected) => {
		isConnected.value = connected
	}

	// 设置事件源
	const setEventSource = (source) => {
		eventSource.value = source
	}

	// 订阅特定类型的消息
	const subscribe = (type, callback) => {
		if (!subscribers.value.has(type)) {
			subscribers.value.set(type, new Set())
		}
		subscribers.value.get(type).add(callback)

		// 返回取消订阅的函数
		return () => {
			unsubscribe(type, callback)
		}
	}

	// 取消订阅
	const unsubscribe = (type, callback) => {
		if (subscribers.value.has(type)) {
			subscribers.value.get(type).delete(callback)
			if (subscribers.value.get(type).size === 0) {
				subscribers.value.delete(type)
			}
		}
	}

	// 通知订阅者
	const notifySubscribers = (message) => {
		const callbacks = subscribers.value.get(message.type)
		if (callbacks) {
			callbacks.forEach((callback) => callback(message))
		}
	}

	// 断开 SSE 连接
	const disconnect = () => {
		if (eventSource.value) {
			eventSource.value.close()
			eventSource.value = null
			isConnected.value = false
			console.log('SSE connection closed')
		}
	}

	// 清空消息
	const clearMessages = () => {
		messages.value = []
	}

	return {
		messages,
		latestMessage,
		isConnected,
		error,
		eventSource,
		getMessagesByType,
		getLatestMessageByType,
		addMessage,
		setConnected,
		setEventSource,
		subscribe,
		unsubscribe,
		disconnect,
		clearMessages
	}
})
